import {
	Button,
	Form,
	Row,
	Col,
	Input,
	Select,
	Cascader,
	message,
	Upload,
} from 'antd'
import React, {useState, useEffect} from 'react'
import {history, useModel} from 'umi'
import type {UploadFile} from 'antd/es/upload/interface'
import {
	editGraderecord,
	graderecordInfo,
	importGraderecord,
} from '@/service/supplier/graderecord'
import styles from './index.less'
import {getDict} from '@/service/common/dict'
import {getSupplierType} from '@/utils/common'
import {getPublicDownloadUrl, uploadFileUrl} from '@/service/common/upload'
import Modal from '@/components/Modal'
import {getTemplateUrl} from '@/service/common/download'

const {Dragger} = Upload

const edit = (props: any) => {
	const {query} = props.location
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const [form] = Form.useForm()
	const [supplierDetail, setSupplierDetail] = useState<any>()
	// 字典数据
	const [dictData, setDictData] = useState<any>({})
	const [fileList, setFileList] = useState<UploadFile[]>([])
	const [supplierTypeData, setSupplierTypeData] =
		useState<supplierAPI.supplierType>([])
	const [formData, setFormData] = useState<any>({})
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [gradeScore, setGradeScore] = useState('')

	useEffect(() => {
		getDict(
			{
				dictKeys: [
					'ZC_GYS',
					'JC_GYS',
					'CZ_GYS',
					'SP_GYS',
					'DYY_GYS',
					'CS_GYS',
					'Supplier_Rating',
				],
			},
			(res: any) => {
				setDictData(res)
				// 组装供应商类型
				const newData = getSupplierType([
					res.ZC_GYS,
					res.JC_GYS,
					res.CZ_GYS,
					res.SP_GYS,
					res.DYY_GYS,
					res.CS_GYS,
				])
				setSupplierTypeData(newData)
			},
		)
	}, [])

	useEffect(() => {
		if (query) {
			graderecordInfo(query?.id).then((res: any) => {
				if (res?.data) {
					setGradeScore(res.data?.gradeList?.[0]?.score)
					setSupplierDetail(res.data)
					const {supplierCode, supplierType, supplierName} = res.data
					form.setFieldsValue({
						supplierCode,
						supplierName,
						supplierType: supplierType.split(','),
						scoreGrade: res.data?.gradeList?.[0]?.scoreGrade,
					})
					const url = res?.data?.gradeList?.[0]?.scoreFile
						?.split(',')
						?.map(Number)
					if (url?.length) {
						getPublicDownloadUrl(url)
							.then((result: any) => {
								const urlData = result?.data?.map(
									(item: {
										id: any
										filename: string
										url: string
									}) => ({
										uid: item?.id,
										name: item?.filename,
										url: item?.url,
									}),
								)
								setFileList(urlData)
							})
							.catch((err: any) => {
								message.error(err)
							})
					}
				}
			})
		}
	}, [query])

	const onSave = async () => {
		form.validateFields()
		const value = await form.validateFields()
		if (value) {
			if (fileList?.length) {
				const urlArr = fileList?.map(
					(item) => item?.response?.data?.id || item?.uid,
				)
				const newData = {
					supplierId: value?.supplierId,
					scoreGrade: value?.scoreGrade,
					supplierType: value?.supplierType.toString(),
					fileList: [
						{
							serviceType: value?.supplierType.toString(),
							url: urlArr?.toString(),
							score: gradeScore?.toString(),
						},
					],
				}
				if (newData?.fileList?.[0]?.score) {
					setFormData(newData)
					setIsModalOpen(true)
				} else {
					message.warning('请上传评分文件')
				}
			} else {
				message.warning('请上传评分文件')
			}
		}
	}
	const onSubmit = () => {
		editGraderecord({...formData, supplierId: query.id})
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
				}
			})
			.catch((err: any) => {
				message.error(err)
			})
	}
	const uploadProps = {
		action: uploadFileUrl,
		name: fileName,
		data: {
			modelName: 'spGrade',
			targetAttr: 1,
		},
		fileList,
		beforeUpload: (file: any) => {
			const isLt20M = file.size / 1024 / 1024 < 200
			if (!isLt20M) {
				message.error('文件必须小于200MB')
			}
			return isLt20M
		},
		onChange(info: any) {
			setFileList(info.fileList)
			if (info.file.status === 'done') {
				const formdata = new FormData()
				formdata.append('file', info?.file?.originFileObj)
				importGraderecord(formdata)
					.then((res: any) => {
						if (res.success) {
							setGradeScore(res?.data?.toString())
							message.success('评分计算成功')
						}
					})
					.catch((error: any) => {
						message.error(error)
					})
				message.success(info?.file?.response.msg)
			} else if (info.file.status === 'error') {
				message.error(info?.file?.response.msg)
			} else if (info.file.status === 'removed') {
				setGradeScore('')
			}
		},
	}
	return (
		<div className={styles.edit}>
			<Form
				form={form}
				name="basic"
				layout="horizontal"
				labelCol={{flex: '140px'}}
				labelAlign="right"
				labelWrap
				autoComplete="off">
				<Row gutter={12}>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="供应商编号"
							name="supplierCode"
							rules={[
								{
									required: true,
								},
							]}>
							<Input placeholder="请输入" disabled />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="供应商类型"
							name="supplierType"
							rules={[{required: true}]}
							colon>
							<Cascader
								options={supplierTypeData}
								placeholder="请选择"
								disabled
							/>
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="供应商名称"
							name="supplierName"
							rules={[
								{
									required: true,
									max: 20,
								},
							]}>
							<Input placeholder="请输入" disabled />
						</Form.Item>
					</Col>
					<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
						<Form.Item
							label="供应商评级"
							name="scoreGrade"
							rules={[{required: true}]}
							className={styles.required}>
							<Select
								placeholder="请选择"
								allowClear
								fieldNames={{
									value: 'dictKey',
									label: 'dictValue',
								}}
								options={dictData?.Supplier_Rating}
							/>
						</Form.Item>
					</Col>
					<Col span={24}>
						<Form.Item label="服务类型" name="serviceType">
							<table border="1" className={styles.uploadWrap}>
								<tr>
									<td>供应商类型</td>
									<td>
										评分文件
										<Button
											type="link"
											shape="round"
											size="small"
											className="downOrupload"
											onClick={() =>
												getTemplateUrl(
													47,
													'供应商评级模板',
												)
											}>
											下载评分模板
										</Button>
									</td>
									<td>得分情况</td>
								</tr>
								<tr>
									<td>
										<Cascader
											value={supplierDetail?.supplierType.split(
												',',
											)}
											options={supplierTypeData}
											disabled
										/>
									</td>
									<td>
										<Dragger {...uploadProps}>
											{fileList?.length < 1 ? (
												<Button type="link">
													请选择文件
												</Button>
											) : (
												''
											)}
										</Dragger>
									</td>
									<td>{gradeScore || '得分'}</td>
								</tr>
							</table>
						</Form.Item>
					</Col>
				</Row>
			</Form>
			<div className={styles.wrap}>
				<Button
					onClick={() => {
						history.go(-1)
					}}>
					取消
				</Button>
				<Button type="primary" htmlType="submit" onClick={onSave}>
					保存
				</Button>
			</div>
			<Modal
				text="确定要保存吗？请仔细核对所填信息"
				onSubmit={onSubmit}
				isModalOpen={isModalOpen}
				setIsModalOpen={setIsModalOpen}
			/>
		</div>
	)
}

export default edit
